# modbus_client.py
from pymodbus.client import ModbusTcpClient
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger("pymodbus.client")

# 客户端请求函数
def send_request(request_str):
    client = ModbusTcpClient('127.0.0.1', port=502)
    client.connect()

    try:
        # 将请求字符串写入寄存器 0-9
        request_data = [ord(c) for c in request_str]
        client.write_registers(0, request_data)

        # 读取服务端的响应（寄存器 10-19）
        response = client.read_holding_registers(10, count=10)
        if response.isError():
            _logger.error(f"Error reading response: {response}")
        else:
            response_str = ''.join(chr(byte) for byte in response.registers).strip('\x00')
            print(f"Response from server: {response_str}")
    finally:
        client.close()

# 测试请求
if __name__ == "__main__":
    send_request("hello")   # 应答 "world"
    send_request("nihao")   # 应答 "good"
    send_request("test")    # 应答 "unknown"